package com.cityguardian.cityguardianapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.cityguardian.model.Alerta;
import com.cityguardian.model.Usuario;
import com.cityguardian.threads.AsyncTaskCorrective;
import com.cityguardian.utils.Utils;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class CorrectiveActivity extends ActionBarActivity {
	
	private String idPostServicio;
	private String acciones;
	private TextView textViewAcciones;
	private String path;
	private Bitmap mImageBitmap;
	private ScrollView scrollView;
	private Usuario usuario;
	private Alerta alerta;
	private boolean hayFoto=false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_corrective);
		// Show the Up button in the action bar.
		setupActionBar();
		
		Intent intent = getIntent();
		idPostServicio=intent.getStringExtra("idPostServicio");
		acciones=intent.getStringExtra("acciones");
		usuario=(Usuario)intent.getSerializableExtra("Usuario");
		alerta=(Alerta)intent.getSerializableExtra("Alerta");
		textViewAcciones = (TextView) findViewById(R.id.textViewAcciones);
		textViewAcciones.setText(acciones);
		scrollView = (ScrollView) findViewById(R.id.scrollViewCorrective);
		
	}
	
	/**
	 * Set up the {@link android.app.ActionBar}, if the API is available.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	private void setupActionBar() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			getActionBar().setDisplayHomeAsUpEnabled(true);
		} else {
		    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.corrective, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	        case R.id.action_button:
	            sendUserForFillActivity();
	            return true;
	        case R.id.number_button:
	        	showSearch();
	        	return true;
	        case R.id.action_search:
	        	showSearch();
	        	return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void sendUserForFillActivity() {
		Intent intent = new Intent(this, FillAlertActivity.class);	
		intent.putExtra("Usuario", this.usuario);
		intent.putExtra("Latitud", Double.parseDouble(alerta.getPosicionY()));
		intent.putExtra("Longitud", Double.parseDouble(alerta.getPosicionX()));
		startActivity(intent);
	}
	
	public void showAlertList() {
	}
	
	private void showSearch(){
		Intent intent = new Intent(this, SearchActivity.class);
		intent.putExtra("Usuario", usuario);
		intent.putExtra("Alerta", alerta);		
		startActivity(intent);
	}
	
	public void onPhotoClick(View view){
		path = Environment.getExternalStorageDirectory()
				+File.separator+"CityGuardian"+File.separator;
		String timeStamp = 
		        new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		path+=timeStamp+".jpg";
		File f=new File( path );
		
		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		startActivityForResult(takePictureIntent, 0);		
	} 
	
	public void onFinalizar(View view){
		
		if (!hayFoto){
			Toast.makeText(getBaseContext(), 
					"Porfavor adjuntar una foto", Toast.LENGTH_LONG).show();
		}else{
			if (Utils.haveNetworkConnection(this)){
				AsyncTaskCorrective thread = new AsyncTaskCorrective(this,path,idPostServicio,usuario);
				thread.execute();
			}			
		}
	}
	
	private void galleryAddPic() {
	    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
	    File f = new File(path);
	    Uri contentUri = Uri.fromFile(f);
	    mediaScanIntent.setData(contentUri);
	    this.sendBroadcast(mediaScanIntent);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
		Log.i( "MakeMachine", "resultCode: " + resultCode );
		
		switch( resultCode )
	    {
	    	case 0:
	    		Log.d( "MakeMachine", "User cancelled" );
	    		break;
	    			
	    	case -1:
	    		handleSmallCameraPhoto(data);
	    		break;
	    }
	}
	
	private void handleSmallCameraPhoto(Intent intent) {

	    BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inSampleSize = 4;
	    mImageBitmap = BitmapFactory.decodeFile( path, options );
	    ImageView imageView = (ImageView) findViewById(R.id.imageViewFoto);  
//	    imageView.setImageBitmap(mImageBitmap); 
	    
	    float scaleFactor = (float)scrollView.getWidth() / (float)mImageBitmap.getWidth();     
	    mImageBitmap = Bitmap.createScaledBitmap(mImageBitmap, (int)(mImageBitmap.getWidth() * scaleFactor), (int)(mImageBitmap.getHeight() * scaleFactor), true);
	    imageView.setImageBitmap(mImageBitmap);
	    LayoutParams params = (LayoutParams) imageView.getLayoutParams();             
	    params.width = mImageBitmap.getWidth();
	    params.height = mImageBitmap.getHeight();
	    imageView.setLayoutParams(params);
	    hayFoto=true;
	    galleryAddPic();
	}
	
}
